﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

public class BLLUser
{
    DatabaseDataContext Context;


    public BLLUser()
	{
        Context = new DatabaseDataContext();
	}
    public bool AuthenticateUser(string username, string password, out string msg)
    {
        bool result = false;
        List<User> userList = new List<User>();
        User user = new User();
        msg = "";
        try
        {
              var us = (from u in Context.Users where u.Username == username 
                            && u.Password == password == true select u);
              userList = us.ToList();
              if (userList.Count() > 0) 
              {
                  user = userList.ElementAt(0);
                  if (!user.IsEnabled)
                  {
                      msg = "Este usuario est&aacute; inactivo.";
                  }
                  else
                  {

                      CreateUserCookies(user,true);
                      result = true;
                      msg = "Inicio de sesion exitoso.";
                  }
              }
              else
                  msg = "Usuario o Contraseña inv&aacute;lido.";
        }
        catch
        {
            msg = "Ocurri&oacute; un problema. Intente nuevamente.";
        }

        return result;
    }
    public User GetEnabledUserById(int Id)
    {
        List<User> userList = new List<User>();
        User user = new User();
        try
        {
            var us = (from u in Context.Users
                      where u.Id == Id && u.IsEnabled == true
                      select u);
            userList = us.ToList();
            if (userList.Count() > 0)
            {
                user = userList.ElementAt(0);
            }
           
        }
        catch
        {
           
        }

        return user;
    }
    public User GetUserById(long Id)
    {
        List<User> userList = new List<User>();
        User user = new User();
        try
        {
            var us = (from u in Context.Users
                      where u.Id == Id
                      select u);
            userList = us.ToList();
            if (userList.Count() > 0)
            {
                user = userList.ElementAt(0);
            }
           
        }
        catch
        {
           
        }

        return user;
    }
    public void CreateUserCookies(User user, bool remember) 
    {
        try
        {
            Util.DeleteCookies(GlobalNames.userCookieInfo);
            HttpCookie Cookie;
            Cookie = new HttpCookie(GlobalNames.userCookieInfo);
            Util.AddCookieValue(Cookie, GlobalNames.UserId, user.Id.ToString());
            Util.AddCookieValue(Cookie, GlobalNames.Username, user.Username);
            Util.AddCookieValue(Cookie, GlobalNames.UserPassword, user.Password);
            Cookie.Expires = DateTime.Now.AddDays(30);
            HttpContext.Current.Response.AppendCookie(Cookie);
            HttpContext.Current.Session[GlobalNames.UserPermissions] = GetUserPermissions(user.Id);
            string value = Util.GetCookieValue(GlobalNames.Username);

        }
        catch 
        {
        
        }
    }
    public List<SessionPermissions> GetUserPermissions(long userId)
    {
        List<SessionPermissions> permissions = new List<SessionPermissions>();
        try
        {
            permissions = (from rp in Context.RolePermissions
                           join p in Context.Permissions
                               on rp.PermissionId equals p.Id
                           join u in Context.Users
                                on rp.RoleId equals u.RoleId
                           where u.Id == userId
                           select new SessionPermissions
                           {
                               ModuleId = p.ModuleId,
                               PermissionId = p.PermissionTypeId,
                           }).ToList(); 
        }
        catch { }
        return permissions;
    }
    public class User_class
    {
        public long Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string FullName { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }
        public string RoleName { get; set; }
        public long RoleId { get; set; }
        public bool IsEnabled { get; set; }
    }
    public List<User_class> GetUsers(string sortExp, string sortDirection, int pageIndex, int filterStatus, String filterSearch, int startRow,
       int pageSize, string sortColumns)
    {
        List<User_class> list = new List<User_class>();
        try
        {
            sortColumns = sortExp + " " + sortDirection;
            startRow = pageIndex * pageSize;
            var users = (from user in Context.Users 
                         select new User_class()
                         {
                            Id = user.Id,
                            FirstName = user.FirstName,
                            LastName = user.LastName,
                            Username = user.Username,
                            FullName = user.FirstName + " " + user.LastName,
                            Email = user.Email,
                            RoleId = user.RoleId,
                            RoleName = user.Role.Name,
                            IsEnabled = user.IsEnabled
                         });
            if (!String.IsNullOrEmpty(filterSearch))
            {
                filterSearch = filterSearch.ToLower();
                users = users.Where(u => u.FirstName.ToLower().Contains(filterSearch) || u.LastName.ToLower().Contains(filterSearch)
                    || u.Email.ToLower().Contains(filterSearch) || u.Username.ToLower().Contains(filterSearch));
            }
            if (filterStatus > 0)
            {
                bool statusB = false;
                switch (filterStatus)
                {
                    case 1:
                        statusB = true;
                        break;
                    default:
                        statusB = false;
                        break;
                }
                users = users.Where(l => l.IsEnabled == statusB);
            }
            if (!String.IsNullOrEmpty(sortColumns))
            {
                if (sortColumns.Contains("DESC"))
                {
                    if (sortColumns.Contains("FullName"))
                        users = users.OrderByDescending(l => l.FullName);
                    if (sortColumns.Contains("Username"))
                        users = users.OrderByDescending(l => l.Username);
                    if (sortColumns.Contains("Email"))
                        users = users.OrderByDescending(l => l.Email);
                    if (sortColumns.Contains("RoleId"))
                        users = users.OrderByDescending(l => l.RoleName);
                    if (sortColumns.Contains("IsEnabled"))
                        users = users.OrderByDescending(l => l.IsEnabled);
                }
                else
                {
                    if (sortColumns.Contains("FullName"))
                        users = users.OrderBy(l => l.FullName);
                    if (sortColumns.Contains("Username"))
                        users = users.OrderBy(l => l.Username);
                    if (sortColumns.Contains("Email"))
                        users = users.OrderBy(l => l.Email);
                    if (sortColumns.Contains("RoleId"))
                        users = users.OrderBy(l => l.RoleName);
                    if (sortColumns.Contains("IsEnabled"))
                        users = users.OrderBy(l => l.IsEnabled);
                }
            }
            list = users.Skip(startRow).Take(pageSize).ToList();
        }
        catch
        { }
        if (list.Count == 0)
        {
            User_class us = new User_class();
            us.Id = -1;
            list.Add(us);
        }
        return list;
    }
    public int GetUsersCount(string sortExp, string sortDirection, int pageIndex, int filterStatus, String filterSearch)
    {
        int count = 0;

        try
        {
            var users = (from user in Context.Users
                         select new User_class()
                         {
                             Id = user.Id,
                             FirstName = user.FirstName,
                             LastName = user.LastName,
                             Username = user.Username,
                             Email = user.Email,
                             RoleId = user.RoleId,
                             RoleName = user.Role.Name,
                             IsEnabled = user.IsEnabled
                         });
            if (!String.IsNullOrEmpty(filterSearch))
            {
                filterSearch = filterSearch.ToLower();
                users = users.Where(u => u.FirstName.ToLower().Contains(filterSearch) || u.LastName.ToLower().Contains(filterSearch)
                    || u.Email.ToLower().Contains(filterSearch) || u.Username.ToLower().Contains(filterSearch));
            }
            if (filterStatus > 0)
            {
                bool statusB = false;
                switch (filterStatus)
                {
                    case 1:
                        statusB = true;
                        break;
                    default:
                        statusB = false;
                        break;
                }
                users = users.Where(l => l.IsEnabled == statusB);
            }
            count = users.Count();
        }
        catch
        { }
        if (count == 0)
        {
            count = 1;
        }
        return count;
    }
    public bool UpdateStatus(long Id)
    {

        bool result = false;
        try
        {
            User user = (from u in Context.Users where u.Id == Id select u).First();
            if (user != null)
            {
                user.IsEnabled = !user.IsEnabled;
                Context.SubmitChanges();
                result = true;
            }
        }
        catch
        {
        }
        return result;
    }
    public List<Role> GetEnabledUserRoles() 
    {
        List<Role> roles = new List<Role>();
        try
        {
            roles = (from r in Context.Roles where r.IsEnabled == true select r).ToList();
        }
        catch { }

        return roles;
    }
    public bool Save(User u,bool changePass)
    {
        bool result = false;
        try
        {
            User user = u;
            if (user.Id > 0)
            {
                user = (from usr in Context.Users where u.Id == usr.Id select usr).First();
                user.FirstName = u.FirstName;
                user.LastName = u.LastName;
                user.Email = u.Email;
                user.RoleId = u.RoleId;
                user.Username = u.Username;
                if (changePass)
                    user.Password = u.Password;
                user.IsEnabled = u.IsEnabled;
            }
            else
            {
                Context.Users.InsertOnSubmit(u);
            }
            Context.SubmitChanges();
            result = true;
        }
        catch
        {
        }
        return result;
    }
}